package com.htdata.iiot.api.tsdb.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.htdata.iiot.api.tsdb.pojo.DeviceNumber;
import com.htiiot.common.db.DbConnectionPool;
import com.htiiot.common.db.JDBCUtils;

public class DNService {
	private DbConnectionPool pool = DbConnectionPool.getPool();

	
	private Map<String, String> getDN(ResultSet rs) throws SQLException {
		Map<String, String> map = new HashMap<String, String>();
		while (rs.next()) {
            
			int tenantId = rs.getInt("tenant_id");
			int deviceId = rs.getInt("device_id");
			Long metricId = rs.getLong("metric_number");
			String deviceNumber = new DeviceNumber(tenantId, deviceId, metricId).toHexString();
			map.put(metricId.toString(), deviceNumber);
		}
		return map;
	}

	public Map<String, String> getDeviceIdsByComponentIds(String comonentIds) {

 		String sql = "SELECT device.tenant_id AS tenant_id,device_comp.device_id AS device_id, "
				+ "device.serial_number AS dsn, device_comp.id AS metric_number "
				+ "FROM thing_device device ,thing_device_component_rel device_comp   "
				+ "WHERE "
				+ " device_comp.deleted = 0  "
				+ "AND device.id = device_comp.device_id  "
				+ "AND device.deleted = 0  "
				+ "AND device_comp.id in ("+comonentIds+")";
		Connection conn = pool.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			return getDN(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.close(ps, rs, conn);
		}
		return null;
	}


}
